$NG.AllReady(function (page, { useUpdateRow, useValuesChange, useUpdateRows, useDataIndexChange }) {
    const mstform = $NG.getCmpApi("p_form_proj_audit");
    const grid1 = $NG.getCmpApi("p_form_proj_audit_inner");
    const grid2 = $NG.getCmpApi("p_form_proj_audit_outer");

    {//初始化逻辑BEGIN
        if (mstform) {
            cntMFilter();
        }
    }//初始化逻辑END

    const getHeadVal = (item) => {
        return mstform.getItem(item).getValue()
    }

    // 表头计算逻辑
    function sumAmtHead(map) {
        map.u_yjhte = map.u_cbsdhs ? map.u_cbsdhs / map.u_cshte : 0
        map.u_yjsrzj = map.u_cbsdhs - map.u_srqr
        map.u_mllzj = map.u_yjsdmll - map.u_srmll
        map.u_yjqkyje = map.u_mllzj * map.u_cbsdhs
    }

    // 表头赋值/计算(封装)
    $NG.setHeadValue = {}
    initHead('p_form_proj_audit',sumAmtHead)
    function initHead(table,fun) {
        const mstform = $NG.getCmpApi(table);
        const val = mstform.getValues()
        const headKey = ["u_cshte", "u_htxe", "u_qdmllb", "u_qzbgje", "u_dqmll",
            "u_sshs", "u_mbsdhs", "u_cbsdhs", "u_sjzje", "u_sjl", "u_czbyje",
            "u_srqr", "u_yjhte", "u_yjsrzj", "u_yjsdmll", "u_srmll", "u_mllzj"]

        // 劫持原表头赋值函数，防止2遍数据不同步
        const option = $NG.updateState
        $NG.updateState = function (...args) {
            // 劫持回调
            const updater = args[0]
            args[0] = function (...args) {
                const temp = updater.apply(this, args)// 调原函数
                const prop = args[0].data[table].setProps
                // 劫持setProps
                args[0].data[table].setProps = function (...args) {
                    if (!args[0].hook) {
                        for (let key in args[0]) {
                            if (headKey.includes(key)) {
                                $NG.setHeadValue.manualSet(key, args[0][key])
                            }
                        }
                    }
                    return prop.apply(this, args)//调原函数
                }
                return temp
            }
            option.apply(this, args) // 调原函数
            console.log(`使用原始表头赋值劫持成功`, args);
        }

        Object.defineProperties($NG.setHeadValue, {
            _sumAmt: { // 赋值渲染 + 表头计算计算
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (key) { // 要跳过的key
                    const map = headKey.reduce((value, item) => {
                        value[item] = this["_" + item]
                        return value
                    }, {})
                    // 表头计算
                    fun(map)

                    if (key) {
                        delete map[key]
                    }
                    console.log(`赋值信息`, map, key);
                    $NG.updateState((updater) => {
                        updater.data[table].setProps({
                            hook: true,
                            ...map
                        })
                    })
                }
            },
            noRender: { // 不进行渲染赋值
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (key, val) {
                    this["_" + key] = val
                }
            },
            manualSet: { // 禁止渲染手输入 但要计算
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (key, val) {
                    this["_" + key] = val
                    this._sumAmt(key)
                }
            },
            manySetVal:{
                writable:false,
                enumerable:true,
                configurable:false,
                value:function(map){
                    for(let key in map){
                        this['_'+key] = map[key]
                    }
                    this._sumAmt()
                }
            }
        })
        // 创建不可枚举字段，让不加 _ 的变量代理私有属性(防异步)
        headKey.forEach(item => {
            Object.defineProperties($NG.setHeadValue, {
                [item]: {
                    enumerable: true,
                    configurable: false,
                    set(val) {
                        this['_' + item] = val
                        if (window._sum_amt_lock) {
                            clearTimeout(window._sum_amt_lock)
                        }
                        window._sum_amt_lock = setTimeout(() => {
                            this._sumAmt()
                        }, 1000)
                    },
                    get() {
                        return this['_' + item]
                    }
                },
            })
            Object.defineProperties($NG.setHeadValue, {
                ["_" + item]: {
                    value: (Number(val[item]) || 0),// 设置初始值
                    writable: true,
                    enumerable: false,
                    configurable: false,
                },
            })
            // 如果发生手输入改变
            useValuesChange(({ args }) => {
                $NG.setHeadValue.manualSet(item, args[0][item])
            }, item)
        })
    }

    if (page.oType == "add") {
        var pc = mstform.getItem("phid_pc");
        getCntCount("p_form_proj_audit", "u_cnt_name", () => {
            getCntMInfoByPhid()
        })
        if (pc.getValue() > "0") {
            cntMFilter()
            getNsInfo_inner(pc.getValue())
            getNsInfo_outer(pc.getValue())

            $NG.execServer("GetAuditInfo", { pc: pc.getValue() }, function (res) {
                if (res.count == "1") {
                    const data = JSON.parse(res.data);
                    const u_cnt_no = data[0].extendObjects.u_cnt_no;
                    const bill_no = data[0].extendObjects.bill_no;
                    const cntid = data[0].extendObjects.cntid;
                    const cntname = data[0].extendObjects.cntname;

                    $NG.updateState((updater) => {
                        updater.data.p_form_proj_audit.setProps({
                            u_cnt_no: u_cnt_no,
                            u_cnt_name: {
                                value: cntid,
                                label: cntname,
                            },
                            u_jsd_no: bill_no,
                        });
                    });
                    getNsInfo_inner(cntid)
                    getNsInfo_outer(cntid)

                }
            });

            var pcname = mstform.getItem("phid_pc").getRawValue().label
            $NG.updateState((updater) => {
                //文本
                updater.data.p_form_proj_audit.setProps({
                    bill_name: pcname + "工程审计",
                });
            })
        }
    }

    // 新增、修改
    if (page.oType != 'view') {
        getSbqdHeadInfoByPhidPc()
        getSjcztbTotalAmt()
        getProjectSybyTotalAmt()
        getSbqdInitFromInfo()
        getCbhsHeadInfo()
    }

    //项目名称变化时自动带入产品线、事业部等
    useValuesChange(({ args }) => {
        const phid_pc = args[0].phid_pc.value;
        if (!phid_pc) return
        cntMFilter()
        getNsInfo_inner(phid_pc)
        getNsInfo_outer(phid_pc)
        var pcname = mstform.getItem("phid_pc").getRawValue().label
        $NG.updateState((updater) => {
            //文本
            updater.data.p_form_proj_audit.setProps({
                bill_name: pcname + "工程审计",
            });
        });

        getCntCount("p_form_proj_audit", "u_cnt_name", () => {
            getCntMInfoByPhid()
        })
        getSbqdHeadInfoByPhidPc()
        getSjcztbTotalAmt()
        getSbqdInitFromInfo()
        getPtInfoByPhid()
    }, "p_form_proj_audit.phid_pc");

    //合同名称变化时自动带入产品线、事业部等
    useValuesChange(({ args }) => {
        const u_cnt_name = args[0].u_cnt_name.value;
        if (!u_cnt_name) return
        $NG.execServer("getAduitHtInfo", { ht: u_cnt_name }, function (res) {
            const data = JSON.parse(res.data);
            const bill_no = data[0].extendObjects.bill_no;
            const u_jsje = data[0].extendObjects.u_jsje;
            $NG.updateState((updater) => {
                updater.data.p_form_proj_audit.setProps({
                    u_jsd_no: bill_no,
                    u_jsje: u_jsje,

                });
            });
        });
        getNsInfo_inner(getHeadVal("u_cnt_name"))
        getNsInfo_outer(getHeadVal("u_cnt_name"))
        getCntMInfoByPhid()
        getProjectSybyTotalAmt()
    }, "p_form_proj_audit.u_cnt_name");


    useUpdateRows(({ args }) => {
        sumAmt()
    }, "p_form_proj_audit_inner");

    useUpdateRows(({ args }) => {
        sumAmt()
    }, "p_form_proj_audit_outer");

    // 表体计算
    function sumAmt() {
        const rows1 = grid1.getRows()
        const rows2 = grid2.getRows()
        
        let u_cbsdhs = 0
        let u_sjzje = 0
        rows1.forEach(item=>{
            u_cbsdhs += (Number(item.u_adjust_jshs) || 0)
            u_sjzje += (Number(item.u_adjust_hsje) || 0)
        })
        rows2.forEach(item=>{
            u_cbsdhs += (Number(item.u_adjust_jshs) || 0)
            u_sjzje += (Number(item.u_adjust_hsje) || 0)
        })

        // 赋值表头
        $NG.setHeadValue.manySetVal({
            u_cbsdhs,
            u_sjzje
        })
    }




    useDataIndexChange(({ args }) => {
        const record = args[0];
        const u_adjust_gcl = record.u_adjust_gcl;
        const u_adjust_prc = record.u_adjust_prc;
        const u_jshsje = record.u_jshsje;
        const taxrate = record.taxrate;

        record.u_adjust_jshs = u_adjust_gcl * u_adjust_prc
        record.u_adjust_hsje = u_jshsje - u_adjust_gcl * u_adjust_prc
        record.u_jsse = u_adjust_gcl * taxrate * u_adjust_prc

        grid1.updateRow(args[0]);
        grid2.updateRow(args[0]);
    }, "u_adjust_gcl");

    useDataIndexChange(({ args }) => {
        const record = args[0];
        const u_adjust_gcl = record.u_adjust_gcl;
        const u_adjust_prc = record.u_adjust_prc;
        const u_jshsje = record.u_jshsje;
        const taxrate = record.taxrate;

        record.u_adjust_jshs = u_adjust_gcl * u_adjust_prc
        record.u_adjust_hsje = u_jshsje - u_adjust_gcl * u_adjust_prc
        record.u_jsse = u_adjust_gcl * taxrate * u_adjust_prc
        grid1.updateRow(args[0]);
        grid2.updateRow(args[0]);

    }, "u_adjust_prc");

    // 获取合同信息
    page.oType != 'view' && getCntMInfoByPhid()
    function getCntMInfoByPhid(params) {
        if (!mstform.getItem("u_cnt_name").getValue()) return
        $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt_name").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(`获取合同信息`, datas);
            $NG.updateState((updater) => {
                updater.data.p_form_proj_audit.setProps({
                    u_cnt_no: datas.pcm_no, //合同编号
                });
            });
            // 计算部分赋值
            $NG.setHeadValue.u_cshte = datas.cnt_amt_init
            $NG.setHeadValue.u_htxe = datas.cnt_sum_vat_fc

        });
    }

    function getPtInfoByPhid() {
        if (mstform.getItem("phid_pc").getValue()) {
            $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(`项目信息`, datas);
                //帮助字段赋值
                $NG.updateState((updater) => {
                    updater.data.p_form_proj_audit.setProps({
                        u_pc_no: datas.pc_no, //项目编号
                        u_agreed_sts_dt: datas.start_date, //计划完工日期
                        u_agreed_pcl_dt: datas.end_date, //计划竣工日期
                        u_xmjl: {
                            value: datas.project_manager_phid,
                            label: datas.project_manager_name,
                        },
                        u_sqgw: {
                            //售前顾问
                            value: datas.user_sqgw_phid,
                            label: datas.user_sqgw_name,
                        },
                        //项目经理
                        phid_emp: {
                            value: datas.project_manager_phid,
                            label: datas.project_manager_name,
                        },
                        //事业部
                        u_division: {
                            value: datas.division_phid,
                            label: datas.division_name,
                        },
                    });
                });
            });
        }
    }

    // 获取设备清单表头信息
    function getSbqdHeadInfoByPhidPc() {
        const phid_pc = getHeadVal("phid_pc")
        if (!phid_pc) return
        $NG.execServer("getSbqdHeadInfoByPhidPc", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_dqmll = _data.u_signed_gm_rate
        })
    }

    // 获取实际产值填报
    function getSjcztbTotalAmt() {
        const phid_pc = getHeadVal("phid_pc")
        if (!phid_pc) return
        $NG.execServer("getSjcztbTotalAmt", { phid_pc }, (res) => {
            if (res.count) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_czbyje = datas.total_amt
        })
    }

    // 获取项目收入报验金额汇总
    function getProjectSybyTotalAmt() {
        const cnt = getHeadVal("u_cnt_name")
        if (!cnt) return
        $NG.execServer("getProjectSybyTotalAmt", { cnt }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)
            $NG.setHeadValue.u_srqr = datas.total_amt_vat
        })
    }

    // 获取设备清单初始单的数据
    function getSbqdInitFromInfo() {
        const phid_pc = getHeadVal("phid_pc")
        if (!phid_pc) return
        $NG.execServer("getSbqdInitFromInfo", { phid_pc }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_qdmllb = datas.u_signed_gm_rate
        })
    }

    // 获取成本核算相关信息
    function getCbhsHeadInfo() {
        const phid_pc = getHeadVal("phid_pc")
        if (!phid_pc) return
        $NG.execServer("getCbhsHeadInfo", { phid_pc }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_srmll = datas.u_ycztwgmll
        })
    }

    //获取合同数量
    function getCntCount(table, key, fun, otherFun) {
        if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
        $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
            switch (res.count) {
                case 0:
                    return;
                case 1:
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    const temp_map = {};
                    temp_map[key] = datas.phid;
                    temp_map[`${key}_EXName`] = datas.bill_name;
                    $NG.updateState((updater) => {
                        updater.data[table].setProps({
                            ...temp_map,
                        });
                        setTimeout(() => {
                            fun();
                            if (otherFun) {
                                otherFun();
                            }
                        }, 200);
                    });
            }
        });
    }

});
function getNsInfo_inner(pcvalue) {
    const grid1 = $NG.getCmpApi("p_form_proj_audit_inner");

    $NG.execServer('GetAduitInner', { pc: pcvalue }, function (res) {
        if (res.count == 0) return
        const data = JSON.parse(res.data);
        var gridArr = []; // 定义表体数组
        var gridCount = res.count; // 增加的行数, 可根据从数据库中取出的数据总数增行
        grid1.clearRows();
        for (var i = 0; i < gridCount; i++) {
            // 列出需要赋值的表体字段
            var gridObj = {};
            gridObj.u_sbqd_no = data[i].extendObjects.u_sbqd_no;
            gridObj.u_sbqd_name = data[i].extendObjects.u_sbqd_name;
            gridObj.u_sbqd_name_EXName = data[i].extendObjects.u_equipment_list_name
            gridObj.u_ggxh = data[i].extendObjects.u_ggxh;
            gridObj.u_jscs = data[i].extendObjects.u_jscs;
            gridObj.u_unit = data[i].extendObjects.u_unit;
            gridObj.u_unit_EXName = data[i].extendObjects.msname;
            gridObj.prc = data[i].extendObjects.prc;
            gridObj.u_adjust_prc = data[i].extendObjects.prc;
            gridObj.qty = data[i].extendObjects.qty;
            gridObj.u_sbqd_qty = data[i].extendObjects.u_sbqd_qty;
            gridObj.u_jsgcl = data[i].extendObjects.u_bsby;
            gridObj.u_adjust_gcl = data[i].extendObjects.u_bsby;
            gridObj.u_jshsje = data[i].extendObjects.u_bsbyhs_amt;
            gridObj.u_adjust_jshs = data[i].extendObjects.u_bsbyhs_amt;
            gridObj.taxrate = data[i].extendObjects.taxrate;
            gridObj.u_jsse = data[i].extendObjects.u_bsbyhs_amt - data[i].extendObjects.u_bsby_amt;
            gridObj.u_adjust_hsje = '0';

            gridArr.push(gridObj);
        }

        // 清空表格内容（放在循环外部）
        grid1.clearRows();

        // 调用新增表体行数据的函数
        grid1.addRows(gridArr);

        // 更新RichHelp字段（如果需要）
        // 这里假设有一个方法可以刷新或重新渲染表格，以确保RichHelp字段正确显示
        grid1.refreshView(); // 或者使用grid.refreshData();
    });



}


function getNsInfo_outer(pcvalue) {
    const grid2 = $NG.getCmpApi("p_form_proj_audit_outer");

    $NG.execServer('GetAuditOuter', { pc: pcvalue }, function (res) {
        if (res.count == 0) return
        const data = JSON.parse(res.data);
        var gridArr = []; // 定义表体数组
        var gridCount = res.count; // 增加的行数, 可根据从数据库中取出的数据总数增行
        grid2.clearRows();
        for (var i = 0; i < gridCount; i++) {
            // 列出需要赋值的表体字段
            var gridObj = {};
            gridObj.u_sbqd_no = data[i].extendObjects.u_sbqd_no;
            gridObj.u_sbqd_name = data[i].extendObjects.u_sbqd_name;
            gridObj.u_sbqd_name_EXName = data[i].extendObjects.u_equipment_list_name
            gridObj.u_ggxh = data[i].extendObjects.u_ggxh;
            gridObj.u_jscs = data[i].extendObjects.u_jscs;
            gridObj.u_unit = data[i].extendObjects.u_unit;
            gridObj.u_unit_EXName = data[i].extendObjects.msname;
            gridObj.prc = data[i].extendObjects.prc;
            gridObj.u_adjust_prc = data[i].extendObjects.prc;
            gridObj.qty = data[i].extendObjects.qty;
            gridObj.u_sbqd_qty = data[i].extendObjects.u_sbqd_qty;
            gridObj.u_jsgcl = data[i].extendObjects.u_bsby;
            gridObj.u_adjust_gcl = data[i].extendObjects.u_bsby;
            gridObj.u_jshsje = data[i].extendObjects.u_bsbyhs_amt;
            gridObj.u_adjust_jshs = data[i].extendObjects.u_bsbyhs_amt;
            gridObj.taxrate = data[i].extendObjects.taxrate;
            gridObj.u_jsse = data[i].extendObjects.u_bsbyhs_amt - data[i].extendObjects.u_bsby_amt;
            gridObj.u_adjust_hsje = '0';

            gridArr.push(gridObj);
        }
        // 清空表格内容（放在循环外部）
        grid2.clearRows();

        // 调用新增表体行数据的函数
        grid2.addRows(gridArr);

        // 更新RichHelp字段（如果需要）
        // 这里假设有一个方法可以刷新或重新渲染表格，以确保RichHelp字段正确显示
        grid2.refreshView(); // 或者使用grid.refreshData();
    });



}
//合同根据项目ID过滤
function cntMFilter() {
    $NG.updateUI((updater, state) => {
        updater.fieldSetForm.p_form_proj_audit.u_cnt_name.setProps({
            onBeforeOpen: async () => {
                var phid_pc = $NG.getCmpApi('p_form_proj_audit').getItem('phid_pc').getValue();
                if (!phid_pc) {
                    $NG.alert("请先选择项目");
                    return false;
                } else {
                    return true;
                }
            },
            ...(!!$NG.getCmpApi('p_form_proj_audit').getItem('phid_pc').getValue() && {
                clientSqlFilter: {
                    'pcm3_cnt_m.phid_pc': $NG.getCmpApi('p_form_proj_audit').getItem('phid_pc').getValue(),
                    
                }
            }),
        });
    });
}